⚡️ Speed up method Color.expand by 28%
#39
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 28% (0.28x) speedup for
Color.expandingradio/themes/utils/colors.py⏱️ Runtime :
543 microseconds→423 microseconds(best of104runs)📝 Explanation and details
The optimization replaces 11 individual attribute lookups with a single tuple access in the
expand()method.Key changes:
_swatchestuple storing all color values during initializationexpand()from creating a list with 11 attribute lookups tolist(self._swatches)Why this is faster:
Reduced attribute lookups: The original code performs 11 separate
self.cXXXattribute lookups (one per color shade), each requiring a dictionary lookup in the object's__dict__. The optimized version stores all values in a pre-built tuple and accesses it once.Tuple to list conversion is faster: Converting a tuple to a list with
list()is a highly optimized C operation that's much faster than building a list element by element with individual attribute accesses.Better memory access pattern: Accessing a single tuple in memory has better cache locality than 11 separate attribute lookups scattered across the object's attribute dictionary.
The line profiler shows the dramatic difference: the original version spent time across 12 lines (448-465μs total), while the optimized version completes in a single line operation (699ns).
Test case performance:
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Color.expand-mhl5jmcfand push.